package com.futvan.z.framework.core;

import com.futvan.z.erp.cms_bunner.cms_bunner;
import com.futvan.z.erp.cms_column.cms_column;
import com.futvan.z.erp.cms_column.cms_column_detail;
import com.futvan.z.erp.cms_info.cms_info;
import com.futvan.z.erp.cms_info.cms_info_detail;
import com.futvan.z.erp.customer.crm_customer;
import com.futvan.z.erp.erp_account_type.erp_account_type;
import com.futvan.z.erp.zproduct.z_product;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.util.*;
import com.futvan.z.system.zaccesskey.z_accesskey;
import com.futvan.z.system.zaccesskey.z_accesskey_ip;
import com.futvan.z.system.zarea.z_area;
import com.futvan.z.system.zcode.z_code;
import com.futvan.z.system.zcode.z_code_detail;
import com.futvan.z.system.zcontroller.z_controller;
import com.futvan.z.system.zcontroller.z_controller_parameter;
import com.futvan.z.system.zdb.z_db;
import com.futvan.z.system.zdb.z_db_table;
import com.futvan.z.system.zdb.z_db_table_column;
import com.futvan.z.system.zetlin.z_etl_in;
import com.futvan.z.system.zetlin.z_etl_in_detail;
import com.futvan.z.system.zform.z_form;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zform.z_form_table_button;
import com.futvan.z.system.zform.z_form_table_column;
import com.futvan.z.system.zhttpservices.z_http_services;
import com.futvan.z.system.zhttpservices.z_http_services_parameter;
import com.futvan.z.system.zjob.z_job;
import com.futvan.z.system.zjob.z_job_run;
import com.futvan.z.system.zlog.z_log;
import com.futvan.z.system.zmenu.z_menu;
import com.futvan.z.system.zorg.z_org;
import com.futvan.z.system.zproject.z_project;
import com.futvan.z.system.zregex.z_regex;
import com.futvan.z.system.zreport.z_report;
import com.futvan.z.system.zreport.z_report_button;
import com.futvan.z.system.zreport.z_report_column;
import com.futvan.z.system.zsequence.z_sequence;
import com.futvan.z.system.zuser.z_user;
import com.futvan.z.system.zusersp.z_user_sp;
import com.futvan.z.system.zworkflow.z_workflow;
import com.futvan.z.system.zworkflow.z_workflow_node;
import com.futvan.z.system.zworkflow.z_workflow_node_branch;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.LiteDeviceResolver;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.socket.WebSocketSession;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.*;

/**
 * Z 超类
 * @author 4223947@qq.com
 * @CreateDate 2018-08-21
 */
@Component
public class SuperZ{
	@Autowired
	public SqlSessionTemplate sqlSession;

	/**
	 * 加载系统参数
	 * @throws Exception
	 */
	public void RLoadParameter() throws Exception {
		//初始化z5显示缓存数据
		z.Z5DisplayValue = new HashMap<String, String>();
		z.Log("初始化z5显示缓存数据集合完成");

		//加载所有系统参数
		initSP();
		z.Log("加载系统参数完成");

		//加载所有项目信息
		initProjects();
		z.Log("加载项目信息完成");

		//加载form信息
		initForms();
		//加载所有用户表单可用按钮
		initUserFunctionButtons();
		z.Log("加载表单信息完成");

		//加载所有表信息
		initTables();
		z.Log("加载所有表信息完成");

		//初始化其它数据库
		initOtherDB();
		z.Log("初始化其它数据库完成");

		//加载所有报表信息
		initReport();
		//加载所有用户报表可用按钮
		initUserReportButtons();
		z.Log("加载所有报表信息完成");

		//加载所有Code信息
		initCode();
		z.Log("加载字典信息完成");

		//加载所有组织信息
		initOrg();
		z.Log("加载所有组织信息完成");

		//加载所有用户
		initUser();
		z.Log("加载所有管理用户信息完成");

		//加载工作流对象
		initWorkFlow();
		z.Log("加载工作流对象信息完成");

		//初始化HTTP接口
		initHttpServices();
		z.Log("加载HTTP接口信息完成");

		//初始化接口密钥
		initAccessKey();
		z.Log("加载接口密钥信息完成");

		//初始化账户类型
		initAccountType();
		z.Log("加载账户类型信息完成");

		//初始化CMS信息
		initCMS();
		z.Log("加载CMS信息完成");

		//加载所有数据抽取记录
		initETL();
		z.Log("加载所有数据抽取记录完成");

		//加载所有产品信息
		initProduct();
		z.Log("加载所以产品信息完成");

		//加载所有Controller方法描述信息
		initControllers();

		//加载所以正则表达式
		initRegexs();
		z.Log("加载所有正则表达式完成");

		//加载所有菜单
		initMenu();
		z.Log("加载所有菜单完成");



	}

	/**
	 *
	 */
	private void initMenu() {
		z.menus = new HashMap<String,z_menu>();
		z.menus_list = sqlSession.selectList("z_menu_select",null);
		for (z_menu m : z.menus_list) {
			z.menus.put(m.getZid(),m);
		}

		//设置面包屑
		for (z_menu m : z.menus_list) {
			bids = "";
			CountBreadcrumbList(m);
			m.setObj(bids);
		}
	}
	String bids;
	private String CountBreadcrumbList(z_menu m) {
		if(z.isNotNull(m)){
			if(z.isNull(bids)){
				bids = m.getZid();
			}else{
				bids = bids+","+m.getZid();
			}

			if(z.isNotNull(m.getParentid())){
				z_menu pm = z.menus.get(m.getParentid());
				CountBreadcrumbList(pm);
			}
		}
		return bids;
	}

	/**
	 * 加载所以正则表达式
	 */
	private void initRegexs() {
		z.regexs = new HashMap<String, z_regex>();
		List<z_regex> list = sqlSession.selectList("z_regex_select",null);
		for (z_regex r : list) {
			z.regexs.put(r.getZid(),r);
		}
	}

	/**
	 * 加载所以产品信息
	 */
	private void initProduct() {
		z.products = new HashMap<String,z_product>();
		List<z_product> list = sqlSession.selectList("z_product_select",null);
		for (z_product p : list) {
			z.products.put(p.getZid(),p);
		}
	}

	/**
	 * 加载所有Controller方法描述信息
	 */
	private void initControllers() {
		if("true".equals(z.sp.get("is_start_controller"))){
			z.controllers = new HashMap<String, z_controller>();
			List<z_controller> list = sqlSession.selectList("z_controller_select", null);
			for (z_controller c : list) {
				List<z_controller_parameter> plist = sqlSession.selectList("z_controller_parameter_select_pid", c.getZid());
				c.setZ_controller_parameter_list(plist);
				z.controllers.put(c.getController(), c);
			}
			z.Log("加载所有Controller描述信息");
		}
	}

	/**
	 * 系统初始时初始化
	 * @throws Exception
	 */
	protected void StartInit() throws Exception {
		//初始化即时通讯对象
		z.socket_session_users = new HashMap<String,List<WebSocketSession>>();
		z.socket_session_id = new HashMap<String,String>();
		z.session_users = new HashMap<String, z_user>();
		z.Log("初始化即时通讯对象完成");

		//初始化行政区域
		initAreas();
		z.Log("加载所有行政获取记录完成");

		//启用系统定时任务
		initJob();

		//删除Fomr表中垃圾数据
		//deleteFormGarbage();

		//初始化环信
//		z.es = EasemobUtil.ConnEMService();
//		z.Log("初始化环信完成");

		//清空temp目录
		clearTemp();
		z.Log("清空temp目录完成");

	}



	/**
	 * 清空temp目录
	 */
	private void clearTemp() {
		String project_path = System.getProperty(z.sp.get("tempfiles"));
		File temp = new File(project_path+"/temp");
		// 判断文件目录是否存在
		if (!temp.exists() && !temp.isDirectory()) {
			//自动创建多级目录
			temp.mkdirs();
		}else {
			FileUtil.clearDir(temp);
		}

	}



	/**
	 * 启用系统定时任务
	 * @throws Exception
	 */
	private void initJob() throws Exception {
		z.jobRunList = new HashMap<String, HashMap<String,String>>();
		z.job_run_info = new HashMap<String,z_job_run>();

		//启动任务工厂
		z.job = StdSchedulerFactory.getDefaultScheduler();
		z.job.start();

		if("true".equals(z.sp.get("isMSN"))) {
			//启用socket清理多任务
			z_job socket_job = new z_job();
			socket_job.setZid(z.newZid());
			socket_job.setIsstart("0");//是否启用
			socket_job.setJobtype("0");//任务类型
			socket_job.setJobname("清理已断开连接用户");
			socket_job.setJobclass("com.futvan.z.framework.core.WebSocketClearUserJob");
			//socket_job.setJobtime("10 * * * * ?");
			socket_job.setJobtime("*/5 * * * * ?");
			JobUtil.jobAdd(socket_job);
		}


		//判读当前系统是否启用系统任务模块
		if("true".equals(z.sp.get("is_start_job"))) {
			//添加系统任务
			String sql = "SELECT * FROM z_job WHERE isstart = 1";
			z_job parameter = new z_job();
			parameter.setIsstart("1");
			List<z_job> jobList = sqlSession.selectList("z_job_select", parameter);
			for (z_job job : jobList) {
				JobUtil.jobAdd(job);
			}
			z.Log("启用系统定时任务完成");
		}
	}


	/**
	 * 加载所有行政区域记录
	 */
	private void initAreas() {
		z.areas = new HashMap<String, z_area>();
		z.lowerArea = new HashMap<String, List<z_area>>();
		List<z_area> list = sqlSession.selectList("z_area_select_sql", "select * from z_area where is_enable = '1' ");
		for (z_area a : list) {
			//获取所有下级地址
			List<z_area> lowerlist = sqlSession.selectList("z_area_select_sql", "select * from z_area where is_enable = '1' and parentid = '"+a.getZid()+"'");
			z.lowerArea.put(a.getZid(), lowerlist);

			//添加到主表对象中
			a.setDetail_list(lowerlist);
			z.areas.put(a.getZid(), a);
		}

	}


	/**
	 * 加载所有数据抽取记录
	 */
	private void initETL() {
		z.etls = new HashMap<String, z_etl_in>();
		List<z_etl_in> etlList = sqlSession.selectList("z_etl_in_select", null);
		for (int i = 0; i < etlList.size(); i++) {
			if(z.isNotNull(etlList.get(i))) {
				//获取明细记录表
				List<z_etl_in_detail> eDetailList = sqlSession.selectList("z_etl_in_detail_select_pid", etlList.get(i).getZid());
				etlList.get(i).setZ_etl_in_detail_list(eDetailList);
				z.etls.put(etlList.get(i).getZid(), etlList.get(i));
			}else {
				continue;
			}

		}

	}


	/**
	 * 初始化CMS信息
	 */
	private void initCMS() {
		z.cms = new HashMap<String, cms_info>();
		z.cmsForNumber = new HashMap<String, cms_info>();
		z.cmsColumn = new HashMap<String, cms_column>();
		z.cmsColumn0List =new ArrayList<cms_column>();
		z.cmsColumnDetail = new HashMap<String, List<cms_column>>();
		z.cmsColumnForNumber = new HashMap<String, cms_column>();
		z.cmsList = new HashMap<String, List<cms_info>>();
		z.cmsListForColumnNumber = new HashMap<String, List<cms_info>>();
		z.cmsBunnerList = new HashMap<String, List<cms_bunner>>();

		//加载所有bunner图片
		z_code c = z.code.get("bunner_group");
		if(z.isNotNull(c)) {
			for (z_code_detail cd : c.getZ_code_detail_list()) {
				cms_bunner cbq = new cms_bunner();
				cbq.setBunner_group(cd.getZ_key());
				List<cms_bunner> bl = sqlSession.selectList("cms_bunner_select", cbq);
				z.cmsBunnerList.put(cd.getZ_key(), bl);
			}
		}

		//获取所有栏目信息
		cms_column cq = new cms_column();
		cq.setIs_enable("1");
		cq.setSql_order_by(" seq ");
		List<cms_column> columnList = sqlSession.selectList("cms_column_select", cq);
		for (cms_column column : columnList) {
			HashMap<String,String> sp = new HashMap<String,String>();
			sp.put("zid", column.getZid());

			//解析URL表达式
			column.setUrl(StringUtil.parseExpression(column.getUrl(), sp));

			//获取附件信息
			cms_column_detail cdq = new cms_column_detail();
			cdq.setSql_order_by(" seq ");
			cdq.setPid(column.getZid());
			List<cms_column_detail> coldetailList = sqlSession.selectList("cms_column_detail_select", cdq);
			column.setCms_column_detail_list(coldetailList);

			//如果没有上级ID，证明是顶级栏目
			if(z.isNull(column.getParentid())) {
				z.cmsColumn0List.add(column);
			}
			z.cmsColumn.put(column.getZid(), column);
			z.cmsColumnForNumber.put(column.getNumber(), column);
			z.cmsColumnDetail.put(column.getZid(), new ArrayList<cms_column>());

			//根据栏目ID，获取所有该栏目信息
			cms_info ciq = new cms_info();
			ciq.setSql_order_by(" istop DESC ,publish_time DESC ");
			ciq.setIs_publish("1");
			ciq.setColumnid(column.getZid());
			List<cms_info> column_cmsList = sqlSession.selectList("cms_info_select", ciq);

			z.cmsList.put(column.getZid(), column_cmsList);
			z.cmsListForColumnNumber.put(column.getNumber(), column_cmsList);
		}

		//获取所有栏目的子栏目
		for (cms_column column : columnList) {
			if(z.isNotNull(column.getParentid())) {
				z.cmsColumnDetail.get(column.getParentid()).add(column);
			}
		}

		//所有所有资讯信息
		cms_info ciq = new cms_info();
		ciq.setIs_publish("1");
		ciq.setSql_order_by(" istop DESC ,publish_time DESC ");
		List<cms_info> cmsList = sqlSession.selectList("cms_info_select", ciq);
		for (cms_info cms : cmsList) {
			//获取明细记录
			List<cms_info_detail> cmsDetailList = sqlSession.selectList("cms_info_detail_select_pid", cms.getZid());
			cms.setCms_info_detail_list(cmsDetailList);
			z.cms.put(cms.getZid(), cms);
			z.cmsForNumber.put(cms.getNumber(), cms);
		}
	}

	/**
	 * 构建其它数据库
	 * @throws Exception
	 */
	private void initOtherDB(){
		z.dbFactorys = new HashMap<String, SqlSessionFactory>();
		z.dbs = new HashMap<String, SqlSessionTemplate>();
		z.dbsMap = new HashMap<String, z_db>();
		z.dbTableMap = new HashMap<String, z_db_table>();
		z.dbTableColumnMap = new HashMap<String, z_db_table_column>();
		List<z_db> list = sqlSession.selectList("z_db_select", null);
		for (z_db c : list) {
			//查询字段信息
			List<z_db_table> tableList = sqlSession.selectList("z_db_table_select_pid", c.getZid());
			for (int i = 0; i < tableList.size(); i++) {
				if(z.isNotNull(tableList.get(i))) {
					//获取字段信息
					List<z_db_table_column> columnList = sqlSession.selectList("z_db_table_column_select_pid", tableList.get(i).getZid());
					for (z_db_table_column col : columnList) {
						z.dbTableColumnMap.put(c.getDbid()+"_"+tableList.get(i).getTable_id()+"_"+col.getColumn_id(), col);
					}
					tableList.get(i).setZ_db_table_column_list(columnList);

					//保存表信息对缓存中
					z.dbTableMap.put(c.getDbid()+"_"+tableList.get(i).getTable_id(), tableList.get(i));
				}else {
					break;
				}
			}
			c.setZ_db_table_list(tableList);
			z.dbsMap.put(c.getDbid(), c);
			//创建SqlSession
			if("z".equals(c.getDbid())) {
				//核心库
				z.dbs.put(c.getDbid(), sqlSession);
			}else {
				//其它库
				DBUtil.CreateSqlSessionTemplate(c);
			}
		}

	}

	/**
	 * 加载所有Form信息
	 */
	private void initForms() {
		z.form_tableid = new HashMap<String, z_form>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT t.table_id,f.form_id,f.form_name,f.project_id,f.isolation_mode,f.isStartQuickQuery  ");
		sql.append(" FROM z_form_table t ");
		sql.append(" LEFT JOIN z_form f ON t.pid = f.zid ");
		sql.append(" WHERE t.parent_table_id IS NULL  OR t.parent_table_id = '' OR LOWER(t.parent_table_id) = 'NULL'  ");
		List<HashMap<String,String>> clist = sqlSession.selectList("select", sql);
		for (HashMap<String, String> c : clist) {
			String tableid = c.get("table_id");
			String form_id = c.get("form_id");
			String form_name = c.get("form_name");
			String project_id = c.get("project_id");
			String isolation_mode = c.get("isolation_mode");
			String isStartQuickQuery = c.get("isStartQuickQuery");
			z_form form = new z_form();
			form.setForm_id(form_id);
			form.setForm_name(form_name);
			form.setProject_id(project_id);
			form.setIsolation_mode(isolation_mode);
			form.setIsStartQuickQuery(isStartQuickQuery);
			z.form_tableid.put(tableid, form);
		}

		z.forms = new HashMap<String, z_form>();
		List<z_form> list = sqlSession.selectList("z_form_select", null);
		for (int i = 0; i < list.size(); i++) {
			z_form f = list.get(i);
			z_form_table tq = new z_form_table();
			tq.setPid(f.getZid());
			tq.setSql_order_by(" seq ");
			List<z_form_table> tableList = sqlSession.selectList("z_form_table_select", tq);
			f.setZ_form_table_list(tableList);
			z.forms.put(f.getZid(), f);
		}
	}


	/**
	 * 初始化账户类型
	 */
	private void initAccountType() {
		z.account_type = new HashMap<String, erp_account_type>();
		List<erp_account_type> list = sqlSession.selectList("erp_account_type_select", null);
		for (erp_account_type at : list) {
			z.account_type.put(at.getZid(), at);
		}
	}


	/**
	 * 	加载所有项目信息
	 */
	private void initProjects() {
		z.projects = new HashMap<String, z_project>();
		z.formidToProjects = new HashMap<String, String>();
		List<z_project> projectlist = sqlSession.selectList("z_project_select", null);
		for (z_project zp : projectlist) {
			z.projects.put(zp.getProject_id(), zp);
		}

		String sql = "SELECT c.form_id,d.project_id FROM z_form c LEFT JOIN z_project d ON c.project_id = d.zid ORDER BY d.project_id DESC";
		List<HashMap<String,String>> clist = sqlSession.selectList("select", sql);
		for (HashMap<String, String> c : clist) {
			z.formidToProjects.put(c.get("form_id"), c.get("project_id"));
		}

		z.formzidToProjects = new HashMap<String, String>();
		String sql2 = "SELECT c.zid,d.project_id FROM z_form c LEFT JOIN z_project d ON c.project_id = d.zid ORDER BY d.project_id DESC";
		List<HashMap<String,String>> c2list = sqlSession.selectList("select", sql2);
		for (HashMap<String, String> c : c2list) {
			z.formzidToProjects.put(c.get("zid"), c.get("project_id"));
		}
	}

	/**
	 * 加载所有用户
	 */
	protected void initUser() {
		z.users = new HashMap<String, z_user>();
		z.users_tel = new HashMap<String, z_user>();
		z.users_userid = new HashMap<String, z_user>();
		z.users_idcard = new HashMap<String, z_user>();
		z.users_sp = new HashMap<String,z_user_sp>();
		List<HashMap<String,String>> clist = sqlSession.selectList("select", "select * from z_user");
		for (HashMap<String, String> c : clist) {
			z_user user = BeanUtil.MapToBean(c, z_user.class);
			z.users.put(user.getZid(), user);
			z.users_tel.put(user.getTel(), user);
			z.users_userid.put(user.getUser_id(), user);
			z.users_idcard.put(user.getIdcard(), user);

			//加载用户参数信息
			List<z_user_sp> splist = sqlSession.selectList("z_user_sp_select_sql", "select * from z_user_sp where uid = '"+user.getZid()+"'");
			for (z_user_sp user_sp : splist) {
				z.users_sp.put(user.getZid()+user_sp.getSpid(), user_sp);
			}
		}

	}

	/**
	 * 初始化接口密钥
	 */
	private void initAccessKey() {
		z.accesskey = new HashMap<String, z_accesskey>();
		String sql = "select * from z_accesskey";
		List<HashMap<String,String>> clist = sqlSession.selectList("select", sql);
		for (HashMap<String, String> c : clist) {
			z_accesskey ak = BeanUtil.MapToBean(c, z_accesskey.class);

			//获取IP信息
			String sql1 = "select * from z_accesskey_ip where pid = '"+ak.getZid()+"'";
			List<HashMap<String,String>> dlist = sqlSession.selectList("select", sql1);
			List<z_accesskey_ip> akiplist = new ArrayList<z_accesskey_ip>();
			for (HashMap<String, String> d : dlist) {
				z_accesskey_ip akip = BeanUtil.MapToBean(d, z_accesskey_ip.class);
				akiplist.add(akip);
			}
			ak.setZ_accesskey_ip_list(akiplist);

			z.accesskey.put(ak.getAccesskeyid(), ak);
		}

	}

	/**
	 * 初始化HTTP接口
	 * @throws Exception
	 */
	private void initHttpServices() throws Exception {
		//		//清空已生成的处理类
		//		String service_sc_path = SystemUtil.getRunClassPath()+"com/futvan/z/httpservices/sc";
		//		//判读目录是否存在，如果没有自动创建
		//		FileUtil.mkdirs(service_sc_path);
		//		boolean result = FileUtil.clearDir(new File(service_sc_path));
		//		if(!result) {
		//			z.Exception("清空接口处理类出错");
		//		}

		//获取接口信息
		z.httpservices = new HashMap<String, z_http_services>();
		z.httpservices_zid = new HashMap<String, z_http_services>();
		String sql = "select * from z_http_services";
		List<HashMap<String,String>> clist = sqlSession.selectList("select", sql);
		for (HashMap<String, String> c : clist) {
			z_http_services cinfo = BeanUtil.MapToBean(c, z_http_services.class);

			//获取IP信息
			String sql1 = "select * from z_http_services_parameter where pid = '"+cinfo.getZid()+"'";
			List<HashMap<String,String>> dlist = sqlSession.selectList("select", sql1);
			List<z_http_services_parameter> dinfolist = new ArrayList<z_http_services_parameter>();
			for (HashMap<String, String> d : dlist) {
				z_http_services_parameter dinfo = BeanUtil.MapToBean(d, z_http_services_parameter.class);
				dinfolist.add(dinfo);
			}
			cinfo.setZ_http_services_parameter_list(dinfolist);

			z.httpservices.put(cinfo.getServiceid(), cinfo);
			z.httpservices_zid.put(cinfo.getZid(), cinfo);

			//			if("0".equals(cinfo.getHttp_services_type())) {
			//				//生成接口处理类并编译
			//				//JavaCompilerUtil.CreateServicesClass(cinfo);
			//			}

		}
	}



	/**
	 * 加载工作流对象
	 */
	private void initWorkFlow() {
		z.wf = new HashMap<String, z_workflow>();
		z.wfListForTableid = new HashMap<String, List<z_workflow>>();
		String sql1 = "select * from z_workflow";
		List<HashMap<String,String>> workflowList = sqlSession.selectList("select", sql1);
		for (HashMap<String, String> workflowMap : workflowList) {
			z_workflow wfInfo = BeanUtil.MapToBean(workflowMap,z_workflow.class);

			//获取节点信息
			String sql2 = "select * from z_workflow_node where pid = '"+wfInfo.getZid()+"' order by seq";
			List<HashMap<String,String>> workflowNodeList = sqlSession.selectList("select",sql2);
			List<z_workflow_node> zwnList = new ArrayList<z_workflow_node>();
			for (HashMap<String, String> workflowNodeMap : workflowNodeList) {
				z_workflow_node wfn = BeanUtil.MapToBean(workflowNodeMap, z_workflow_node.class);

				//获取所有分支节点条件
				String sql5 = "select * from z_workflow_node_branch where pid = '"+wfn.getZid()+"' order by seq";
				List<HashMap<String,String>> branchMapList = sqlSession.selectList("select",sql5);
				List<z_workflow_node_branch> branchList = new ArrayList<z_workflow_node_branch>();
				for (HashMap<String, String> branchMap : branchMapList) {
					z_workflow_node_branch branch = BeanUtil.MapToBean(branchMap, z_workflow_node_branch.class);
					branchList.add(branch);
				}
				wfn.setZ_workflow_node_branch_list(branchList);


				zwnList.add(wfn);
			}
			wfInfo.setZ_workflow_node_list(zwnList);

			z.wf.put(wfInfo.getZid(), wfInfo);
		}

		for (Map.Entry<String, z_form_table> entry : z.tables.entrySet()) {
			//根据表ID获取绑定流程
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT zw.* ");
			sql.append("FROM z_workflow zw ");
			sql.append("INNER JOIN z_form zf ON  zw.w_form = zf.zid ");
			sql.append("INNER JOIN z_form_table zft ON zf.zid = zft.pid ");
			sql.append("WHERE zw.is_start = '1' AND  zft.table_id = '"+entry.getValue().getTable_id()+"' ");
			List<z_workflow> list = sqlSession.selectList("z_workflow_select_sql",sql);
			if(z.isNotNull(list) && list.size()>0) {
				z.wfListForTableid.put(entry.getValue().getTable_id(), list);
			}
		}

	}

	/**
	 * 加载所有报表信息
	 */
	public void initReport() {
		z.reports = new HashMap<String, z_report>();
		z.reportColumns = new HashMap<String, z_report_column>();

		String sql1 = "select * from z_report order by seq ";
		List<HashMap<String,String>> reportList = sqlSession.selectList("select",sql1);
		for (HashMap<String, String> reprotMap : reportList) {
			//获取报表主表对象
			z_report r = BeanUtil.MapToBean(reprotMap, z_report.class);

			//获取报表明细表对象
			String sql2 = "select * from z_report_column where pid = '"+reprotMap.get("zid")+"' order by seq";
			List<HashMap<String,String>> reportDetailList = sqlSession.selectList("select",sql2);
			List<z_report_column> z_report_column_list = new ArrayList<z_report_column>();
			for (HashMap<String, String> reprotDetailMap : reportDetailList) {
				z_report_column rd = BeanUtil.MapToBean(reprotDetailMap, z_report_column.class);
				z_report_column_list.add(rd);

				//保存每个报表字段
				z.reportColumns.put(r.getReportid()+"_"+rd.getColumn_id(), rd);
			}
			r.setZ_report_column_list(z_report_column_list);


			//获取按钮对象
			String sql3 = "select * from z_report_button where pid = '"+reprotMap.get("zid")+"' order by seq";
			List<HashMap<String,String>> reportButtonDetailList = sqlSession.selectList("select",sql3);
			List<z_report_button> z_report_button_list = new ArrayList<z_report_button>();
			for (HashMap<String, String> reprotButtonDetailMap : reportButtonDetailList) {
				z_report_button rbd = BeanUtil.MapToBean(reprotButtonDetailMap, z_report_button.class);
				z_report_button_list.add(rbd);
			}
			r.setZ_report_button_list(z_report_button_list);

			//保存到系统缓存中
			z.reports.put(r.getZid(), r);
		}
	}



	private void initUserFunctionButtons() {
		z.UserFunctionButtons = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer();

		sql.append("  SELECT DISTINCT CONCAT(zru.userid,'-',zmfb.buttonId) userbutton ");
		sql.append("  FROM z_role zr  ");
		sql.append("  INNER JOIN z_role_user zru ON zr.zid = zru.pid ");
		sql.append("  INNER JOIN z_org zo ON zr.orgid = zo.zid ");
		sql.append("  INNER JOIN z_role_menu zrm ON zr.zid = zrm.pid ");
		sql.append("  INNER JOIN z_menu_form_button zmfb ON zrm.menuid = zmfb.pid ");

		List<HashMap<String,String>> UserFunctionButtonsList = sqlSession.selectList("select",sql);
		for (HashMap<String,String> buttonsMap : UserFunctionButtonsList) {
			z.UserFunctionButtons.put(buttonsMap.get("userbutton"), buttonsMap.get("userbutton"));
		}
	}

	private void initUserReportButtons() {
		z.UserReportButtons = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer();
		sql.append("  SELECT DISTINCT CONCAT(zru.userid,'-',zmfb.buttonId) userbutton ");
		sql.append("  FROM z_role zr  ");
		sql.append("  INNER JOIN z_role_user zru ON zr.zid = zru.pid ");
		sql.append("  INNER JOIN z_org zo ON zr.orgid = zo.zid ");
		sql.append("  INNER JOIN z_role_menu zrm ON zr.zid = zrm.pid ");
		sql.append("  INNER JOIN z_menu_report_button zmfb ON zrm.menuid = zmfb.pid ");

		List<HashMap<String,String>> UserReportButtonsList = sqlSession.selectList("select",sql);
		for (HashMap<String,String> buttonsMap : UserReportButtonsList) {
			z.UserReportButtons.put(buttonsMap.get("userbutton"), buttonsMap.get("userbutton"));
		}
	}


	/**
	 * 初始化系统参数
	 * @throws Exception
	 */
	private void initSP() throws Exception{
		z.sp = new HashMap<String, String>();
		//获取z.properties中的参数
		try {
			Properties prop = new Properties();
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("z.properties");
			prop.load(in);
			for (String key : prop.stringPropertyNames()) {
				if(key.equals("tempfiles") && z.isNull(prop.getProperty(key).trim())){
					//创建临时路径
					FileUtil.mkdirs(System.getProperty("user.home"));
					z.sp.put(key, System.getProperty("user.home"));
				}else{
					z.sp.put(key, prop.getProperty(key).trim());
				}
			}
			//获取z_sp参数表中的参数
			List<HashMap<String,String>> spList = sqlSession.selectList("select","SELECT spid,spname,spvalue FROM z_sp ORDER BY seq ");
			if(spList.size()>0) {
				for (HashMap<String,String> spMap : spList) {
					z.sp.put(spMap.get("spid"), spMap.get("spvalue"));
					if("zversion".equals(spMap.get("spid"))) {
						UpdateReadmePropertiesVersionNumber(spMap.get("spvalue"));
					}
				}
			}else {
				z.Exception("获取z_sp参数失败");
			}
		} catch (IOException e) {
			z.Error("初始化系统参数出错", e);
		}

	}



	/**
	 * 修改发布说明文件中版本号
	 * @param VersionNumber
	 * @return
	 */
	private boolean UpdateReadmePropertiesVersionNumber(String VersionNumber) {
		boolean result = false;
		try {
			if(z.isNotNull(VersionNumber) && SystemUtil.isIDE()) {
				Properties prop = new Properties();
				String path = z.sp.get("project_path")+"\\src\\main\\webapp\\readme.properties";
				if(new File(path).isFile()) {
					FileInputStream fis = new FileInputStream(path);
					prop.load(fis);
					fis.close(); //关闭流
					if(!VersionNumber.equals(prop.get("version_number"))){
						prop.setProperty("version_number", VersionNumber);
						// 文件输出流
						FileOutputStream fos = new FileOutputStream(path);
						// 将Properties集合保存到流中
						prop.store(fos, "readme");
						fos.close(); // 关闭流
					}
				}else {
					z.Log("在源码中未找到readme.properties资源文件，无法初始化Z平台版本号，该问题不影响平台运行。");
				}
			}
		} catch (Exception e) {
			z.Error("修改发布说明文件中版本号出错|SuperZ.UpdateReadmePropertiesVersionNumber", e);
		}
		return result;
	}

	/**
	 * 初始化组织信息
	 */
	private void initOrg() {
		//所有组织
		z.orgs = new HashMap<String,z_org>();
		//所有下级组织
		z.lowerOrgids = new HashMap<String, List<String>>();

		String sql = "select * from z_org order by parentid,seq";
		List<HashMap> orgList = sqlSession.selectList("select", sql);
		for (HashMap orgMap : orgList) {
			z_org org = BeanUtil.MapToBean(orgMap, z_org.class);
			z.orgs.put(org.getZid(), org);

			//如果上级组织对象不为空
			if(z.isNotNull(z.lowerOrgids.get(org.getParentid()))) {
				z.lowerOrgids.get(org.getParentid()).add(org.getZid());
			}else {
				List<String> orglist = new ArrayList<String>();
				orglist.add(org.getZid());
				z.lowerOrgids.put(org.getParentid(), orglist);
			}
		}

		//所有下级组织的用户
		z.lowerOrgUsers = new HashMap<String,List<String>>();
		//获取获取组织下级用户
		for (Map.Entry<String, List<String>> entry : z.lowerOrgids.entrySet()) {
			String orgid = entry.getKey();
			List<String> lowerOrgidList = entry.getValue();
			if(z.isNotNull(orgid) && z.isNotNull(lowerOrgidList) && lowerOrgidList.size()>0) {
				String lowerOrgidListString = StringUtil.ListToString(lowerOrgidList, ",", "'", "'");
				List<String> useridlist = sqlSession.selectList("selectone", "select userid from z_org_user where pid in("+lowerOrgidListString+")");
				z.lowerOrgUsers.put(orgid,useridlist);
			}
		}


	}

	/**
	 * 加载所有表信息
	 */
	protected void initTables() {
		z.tables =new HashMap<String, z_form_table>();
		z.tablesForZid = new HashMap<String, z_form_table>();
		z.columns = new HashMap<String, z_form_table_column>();
		z.columnsForColumnZid = new HashMap<String, z_form_table_column>();
		z.buttons = new HashMap<String, z_form_table_button>();
		z.buttonsForZid = new HashMap<String, z_form_table_button>();

		List<HashMap> tableList = sqlSession.selectList("select","SELECT * FROM z_form_table ORDER BY seq ");
		for (HashMap tableMap : tableList) {
			//Map转Bean
			z_form_table t = BeanUtil.MapToBean(tableMap, z_form_table.class);

			//加载明细表
			List<z_form_table> tableDetailList = new ArrayList<z_form_table>();
			for (HashMap tableDetailMap : tableList) {
				z_form_table td = BeanUtil.MapToBean(tableDetailMap, z_form_table.class);
				if(t.getTable_id().equals(td.getParent_table_id())) {

					List<z_form_table_column> dList = new ArrayList<z_form_table_column>();
					List<HashMap> columnList = sqlSession.selectList("select", "SELECT * FROM z_form_table_column where pid = '"+td.getZid()+"' order by seq ");
					for (HashMap columnMap : columnList) {
						z_form_table_column tdcolumn = BeanUtil.MapToBean(columnMap, z_form_table_column.class);
						dList.add(tdcolumn);

						//添加字段到成员变量
						z.columns.put(td.getTable_id()+"_"+tdcolumn.getColumn_id(), tdcolumn);
						z.columnsForColumnZid.put(tdcolumn.getZid(), tdcolumn);
					}
					td.setZ_form_table_column_list(dList);

					//获取明细表按钮
					//根据表名获取所有按钮
					List<z_form_table_button> dbList = new ArrayList<z_form_table_button>();
					List<HashMap> dbuttonList = sqlSession.selectList("select", "SELECT * FROM z_form_table_button where pid = '"+td.getZid()+"' order by seq ");
					for (HashMap columnMap : dbuttonList) {
						z_form_table_button tdcolumn = BeanUtil.MapToBean(columnMap, z_form_table_button.class);
						dbList.add(tdcolumn);

						//添加按钮到成员变量
						z.buttons.put(td.getTable_id()+"_"+tdcolumn.getButton_id(), tdcolumn);
						z.buttonsForZid.put(tdcolumn.getZid(), tdcolumn);
					}
					td.setZ_form_table_button_list(dbList);

					tableDetailList.add(td);

				}
			}
			t.setZ_form_table_detail_list(tableDetailList);

			//根据表名获取表字段
			List<z_form_table_column> dList = new ArrayList<z_form_table_column>();
			List<HashMap> columnList = sqlSession.selectList("select", "SELECT * FROM z_form_table_column where pid = '"+t.getZid()+"' order by seq ");
			for (HashMap columnMap : columnList) {
				z_form_table_column tdcolumn = BeanUtil.MapToBean(columnMap, z_form_table_column.class);
				dList.add(tdcolumn);

				//添加字段到成员变量
				z.columns.put(t.getTable_id()+"_"+tdcolumn.getColumn_id(), tdcolumn);
				z.columnsForColumnZid.put(tdcolumn.getZid(), tdcolumn);
			}
			t.setZ_form_table_column_list(dList);


			//根据表名获取所有按钮
			List<z_form_table_button> bList = new ArrayList<z_form_table_button>();
			List<HashMap> buttonList = sqlSession.selectList("select", "SELECT * FROM z_form_table_button where pid = '"+t.getZid()+"' order by seq ");
			for (HashMap columnMap : buttonList) {
				z_form_table_button tdcolumn = BeanUtil.MapToBean(columnMap, z_form_table_button.class);
				bList.add(tdcolumn);

				//添加按钮到成员变量
				z.buttons.put(t.getTable_id()+"_"+tdcolumn.getButton_id(), tdcolumn);
				z.buttonsForZid.put(tdcolumn.getZid(), tdcolumn);
			}
			t.setZ_form_table_button_list(bList);

			//将获取到的表信息保存到成员变量中
			z.tables.put(t.getTable_id(), t);
			z.tablesForZid.put(t.getZid(), t);
		}
	}


	/**
	 * 加载Code信息
	 */
	protected void initCode() {
		z.code = new HashMap<String, z_code>();
		z.code_detail = new HashMap<String,z_code_detail>();
		z.codeValue = new HashMap<String, String>();
		List<HashMap> code_c_list = sqlSession.selectList("select","SELECT * FROM z_code  ORDER BY z_number ");
		for (HashMap code_c : code_c_list) {
			//Map转Bean
			z_code c = BeanUtil.MapToBean(code_c, z_code.class);

			//根据ZID获取明细
			List<HashMap> code_detail_list = sqlSession.selectList("select","SELECT * FROM z_code_detail zd WHERE pid = '"+c.getZid()+"' order by seq ");
			List<z_code_detail> detailList = new ArrayList<z_code_detail>();
			for (HashMap code_d : code_detail_list) {
				z_code_detail d = BeanUtil.MapToBean(code_d, z_code_detail.class);
				detailList.add(d);
				//成员Code内容成员变量
				z.codeValue.put(c.getZ_number()+"_"+d.getZ_key(), d.getZ_value());
				z.code_detail.put(c.getZ_number()+"_"+d.getZ_key(), d);
			}
			//设置Code明细
			c.setZ_code_detail_list(detailList);

			//将Code信息保存在成员变量中
			z.code.put(c.getZ_number(), c);
		}


	}

	/**
	 * 删除Fomr表中垃圾数据
	 */
	public void deleteFormGarbage() {

		//删除按钮表垃圾数据
		StringBuffer sql1 = new StringBuffer();
		sql1.append("DELETE FROM z_form_table_button d WHERE d.zid IN ( ");
		sql1.append("SELECT n.zid FROM ( ");
		sql1.append("	SELECT tb.zid ");
		sql1.append("	FROM z_form_table_button tb ");
		sql1.append("	LEFT JOIN z_form_table t ON tb.pid = t.zid ");
		sql1.append("	WHERE t.zid IS NULL OR t.zid =''  ");
		sql1.append("");
		sql1.append(") n )");
		sqlSession.delete("delete", sql1);

		//删除字段表垃圾数据
		StringBuffer sql2 = new StringBuffer();
		sql2.append("DELETE FROM z_form_table_column d WHERE d.zid IN ( ");
		sql2.append("SELECT n.zid FROM ( ");
		sql2.append("	SELECT tb.zid ");
		sql2.append("	FROM z_form_table_column tb ");
		sql2.append("	LEFT JOIN z_form_table t ON tb.pid = t.zid ");
		sql2.append("	WHERE t.zid IS NULL OR t.zid =''  ");
		sql2.append("");
		sql2.append(") n )");
		sqlSession.delete("delete", sql2);

		//删除表垃圾数据
		StringBuffer sql3 = new StringBuffer();
		sql3.append("DELETE FROM z_form_table d WHERE d.zid IN ( ");
		sql3.append("SELECT n.zid FROM ( ");
		sql3.append("	SELECT t.zid ");
		sql3.append("	FROM z_form_table t ");
		sql3.append("	LEFT JOIN z_form f ON t.pid = f.zid ");
		sql3.append("	WHERE f.zid IS NULL OR f.zid = ''  ");
		sql3.append("");
		sql3.append(") n )");
		sqlSession.delete("delete", sql3);

	}


	/**
	 * 生成日志标题
	 * @return
	 */
	protected String CreateLogtitle(HttpServletRequest request,HandlerMethod method) {
		String title = "";
		z_controller c = z.controllers.get(method.getMethod().getName());
		if(z.isNotNull(c) && "1".equals(c.getIs_monitor())) {
			title = c.getName();

			String tableId = request.getParameter("tableId");
			if(z.isNotNull(tableId)) {
				z_form_table table = z.tables.get(tableId);
				if(z.isNotNull(table)) {
					title = title + " | 操作表："+table.getTable_title()+"【"+table.getTable_id()+"】";
				}
			}

		}else{
			title = method.getMethod().getName();
		}
		return title;
	}

	/**
	 * 获取多选框值[表单]
	 * @param column 字段
	 * @param values
	 * @return
	 */
	public String CheckedValue(z_form_table_column column, String values) {
		String returnvalue = " | ";
		if(!"".equals(column.getP_code_id()) && column.getP_code_id()!=null) {
			z_code code = z.code.get(column.getP_code_id());
			if(code!=null && code.getZ_code_detail_list().size()>0) {
				List<z_code_detail> delailList = code.getZ_code_detail_list();
				for (z_code_detail code_d : delailList) {
					if(isChecked(values,code_d.getZ_key())) {
						returnvalue = returnvalue + code_d.getZ_value()+" | ";
					}
				}
			}
		}
		return returnvalue;
	}

	/**
	 * 获取Code显示颜色
	 * @param codeid_key 代码编号
	 * @return 文字颜色CSS代码
	 */
	public String CodeValueColor(String codeid_key,String displayValue) {
		z_code_detail  zcd = z.code_detail.get(codeid_key);
		if(z.isNotNull(zcd) && z.isNotNull(zcd.getDisplay_color())) {
			return "<span style=\"color:#"+zcd.getDisplay_color()+";\">"+displayValue+"</span>";
		}else {
			return displayValue;
		}
	}

	/**
	 * 显示TD
	 * @param column
	 * @param bean
	 * @return
	 */
	public String printTd(String displayValue,z_form_table_column column, HashMap<String, String> bean) {
		String tdValue = "";
		String tr_href = column.getTr_href();//获取列表行链接
		if(z.isNotNull(tr_href)) {
			//解析链接变量
			String tr_href_parse_value = StringUtil.parseExpression(tr_href, bean);
			//如果链接中包括http，自动以新窗口找开
			String target = "";
			if(tr_href_parse_value.toLowerCase().indexOf("http")>=0) {
				target = "target='_blank'";
			}
			tdValue = "<a href='"+tr_href_parse_value+"' class='TableUrlA' "+target+" >"+displayValue+"</a>";
		}else {
			tdValue = displayValue;
		}
		return tdValue;
	}

	/**
	 * 获取多选框值[报表]
	 * @param column 字段
	 * @param values
	 * @return
	 */
	public String CheckedValueR(z_report_column column, String values) {
		String returnvalue = " | ";
		if(!"".equals(column.getP_code_id()) && column.getP_code_id()!=null) {
			z_code code = z.code.get(column.getP_code_id());
			if(code!=null && code.getZ_code_detail_list().size()>0) {
				List<z_code_detail> delailList = code.getZ_code_detail_list();
				for (z_code_detail code_d : delailList) {
					if(isChecked(values,code_d.getZ_key())) {
						returnvalue = returnvalue + code_d.getZ_value()+" | ";
					}
				}
			}
		}
		return returnvalue;
	}

	/**
	 * 判读多选框是否选中
	 * @param values
	 * @param z_key
	 * @return
	 */
	public boolean isChecked(String values, String z_key) {
		boolean returnvalue = false;
		//值转为数据
		String[] valuearray = values.split(",");
		for (int i = 0; i < valuearray.length; i++) {
			String v = valuearray[i];
			//判读数组中每个值是否选择
			if(v.equals(z_key)) {
				returnvalue = true;
			}
		}
		return returnvalue;
	}

	/**
	 *	下拉框是否选中
	 * @param key
	 * @param comparisonType
	 * @return
	 */
	public String isSelected(String key, String comparisonType) {
		if(key.equals(comparisonType)) {
			return " selected=\"selected\" ";
		}else {
			return "";
		}
	}

	/**
	 * 	获取单选多选排列方向
	 * @param arrangement_direction
	 * @return
	 */
	protected String GetArrangementDirectionCss(String arrangement_direction) {
		if("1".equals(arrangement_direction)) {
			return "float_left";
		}else {
			return " ";
		}
	}

	/**
	 * 	多选框，单选框是否选中
	 * @param key
	 * @param comparisonType
	 * @return
	 */
	public String isRadioChecked(String key, String comparisonType) {
		if(key.equals(comparisonType)) {
			return " checked=\"checked\" ";
		}else {
			return "";
		}
	}

	/**
	 * 设置是否非空
	 * @param Is_Null
	 * @return
	 */
	public String ColumnIsNull(String  Is_Null) {
		if("1".equals(Is_Null)) {
			return " required ";
		}else {
			return "";
		}
	}

	/**
	 * 设置是否只读
	 * @param Is_readonly
	 * @return
	 */
	public String ColumnIsReadonly(String  Is_readonly) {
		if("1".equals(Is_readonly)) {
			return " readonly ";
		}else {
			return "";
		}
	}

	/**
	 * 设置是否只读
	 * @param Is_readonly
	 * @return
	 */
	public String ColumnIsDisabled(String  Is_readonly) {
		if("1".equals(Is_readonly)) {
			return " disabled ";
		}else {
			return "";
		}
	}

	/**
	 * 获取Z5显示值【表单】
	 * @param column
	 * @param columnValue
	 * @return
	 */
	public String getZ5DisplayValue(z_form_table_column column, String columnValue) {
		if(!"".equals(column.getZ5_table()) && column.getZ5_table()!=null && !"".equals(column.getZ5_key()) && column.getZ5_table()!=null && !"".equals(columnValue) && columnValue!=null) {
			String key = column.getZ5_table()+column.getZ5_key()+columnValue;
			String DisplayValue = z.Z5DisplayValue.get(key);
			if(!"".equals(DisplayValue) && DisplayValue!=null) {
				return DisplayValue;
			}else {
				String sql = "select "+column.getZ5_value() +" from "+column.getZ5_table()+" where "+column.getZ5_key() +" = '"+columnValue+"'";
				List<String> list = sqlSession.selectList("selectone", sql);
				if(list.size()>0) {
					String DValue = list.get(0);
					z.Z5DisplayValue.put(key, DValue);
					return DValue;
				}else {
					return columnValue;
				}
			}
		}else {
			return columnValue;
		}


	}

	/**
	 * 获取Z5显示值【表单】
	 */
	public String getZ5DisplayValue(String z5_table,String z5_key,String z5_value, String columnValue) {
		z_form_table_column column = new z_form_table_column();
		column.setZ5_table(z5_table);
		column.setZ5_key(z5_key);
		column.setZ5_value(z5_value);
		return getZ5DisplayValue(column,columnValue);
	}

	/**
	 * 获取Z5显示值【报表】
	 */
	public String getZ5DisplayValueR(z_report_column column, String columnValue) {
		if(!"".equals(column.getZ5_table()) && column.getZ5_table()!=null && !"".equals(column.getZ5_key()) && column.getZ5_table()!=null && !"".equals(columnValue) && columnValue!=null) {
			String key = column.getZ5_table()+column.getZ5_key()+columnValue;
			String DisplayValue = z.Z5DisplayValue.get(key);
			if(!"".equals(DisplayValue) && DisplayValue!=null) {
				return DisplayValue;
			}else {
				String sql = "select "+column.getZ5_value() +" from "+column.getZ5_table()+" where "+column.getZ5_key() +" = '"+columnValue+"'";
				List<String> list = sqlSession.selectList("selectone", sql);
				if(list.size()>0) {
					String DValue = list.get(0);
					z.Z5DisplayValue.put(key, DValue);
					return DValue;
				}else {
					return columnValue;
				}
			}
		}else {
			return columnValue;
		}


	}

	/**
	 * 根据用户 登陆账号 / 手机号 /ZID 查询用户
	 * @param userinfo
	 * @return
	 * @throws Exception
	 */
	public z_user GetDBUser(String userinfo) throws Exception {
		z_user user = null;
		String sql = "select * from z_user where zid = '"+userinfo+"' or user_id = '"+userinfo+"' or tel = '"+userinfo+"'";
		List<z_user> userList = sqlSession.selectList("z_user_select_sql", sql);
		if(z.isNotNull(userList) && userList.size()>0) {
			if(userList.size()>1) {
				z.Exception("登录账号产生重复信息，请使用手机号进行登录");
			}else {
				user = userList.get(0);
			}
		}else {
			z.Log("GetDBUser：根据【"+userinfo+"】未从数据库中获取到用户信息");
		}
		return user;
	}

	/**
	 * 向在线用户表中上传用户信息
	 * @param request
	 * @param user
	 * @return
	 */
	public boolean SetSessionUser(HttpServletRequest request,z_user user,String orgid) {
		boolean result = false;
		if(request!=null && user!=null) {
			//保存用户信息到Session中
			request.getSession().setAttribute("zuser", user);
			//保存用户组织信息到Session中
			z_org org = GetOrg(orgid);
			request.getSession().setAttribute("zorg", org);
			//添加系统常用参数
			request.getSession().setAttribute("sp", z.sp);
			//获取用户消息列表
			Result r = GetUserMessageList(user.getZid());
			request.getSession().setAttribute("user_messages_list", r.getData());
		}
		return result;
	}

	/**
	 * 刷新SessionUsers
	 */
	public void RefreshSessionUser(HttpServletRequest request) {
		request.getSession().setAttribute("session_users", z.session_users);
		String userId = GetSessionUserId(request);

		//清理Session表中已下线的用户
		List<String> now_session_userid_list = new ArrayList<String>();
		for (String uid : z.session_users.keySet()) {
			now_session_userid_list.add(uid);
		}
		if(now_session_userid_list.size()==0) {
			sqlSession.delete("delete", "delete from z_user_online");
		}else {
			String uids = StringUtil.ListToString(now_session_userid_list, ",", "'", "'");
			sqlSession.delete("delete", "delete from z_user_online where userid not in("+uids+")");
		}



		//获取用户消息列表
		Result r = GetUserMessageList(userId);
		request.getSession().setAttribute("user_messages_list", r.getData());
	}

	/**
	 * Session销毁时删除在线用户中的记录
	 */
	public void DeleteSessionUser(String SessionId) {
		String sql = "DELETE FROM z_user_online WHERE sessionid = '"+SessionId+"'";
		sqlSession.delete("delete", sql);
	}

	/**
	 * 	从在线用户表中获取用户
	 * @param request
	 * @return
	 */
	public z_user GetSessionUser(HttpServletRequest request) {
		z_user user = null;
		if(request!=null) {
			String sessionid = request.getSession().getId();
			//根据SessionId查询当前在线用户
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT zu.* FROM z_user_online zuo ");
			sql.append(" INNER JOIN z_user zu ON zuo.userid = zu.zid  ");
			sql.append(" WHERE zuo.sessionid = '"+sessionid+"'");
			HashMap userMap = sqlSession.selectOne("select",sql);
			if(userMap!=null) {
				user = BeanUtil.MapToBean(userMap, z_user.class);
			}
		}
		return user;
	}

	/**
	 * 	从Session中获取用户ID
	 *
	 * @param request
	 * @return
	 */
	public static String GetSessionUserId(HttpServletRequest request) {
		String userId = "";
		if(request!=null) {
			Object userObj = request.getSession().getAttribute("zuser");
			if(userObj!=null && userObj instanceof z_user) {
				z_user user = (z_user) userObj;
				userId = user.getZid();
			}
		}
		return userId;
	}

	/**
	 * 获取当前登录用户所登录的组织
	 * @param request
	 * @return
	 */
	public String GetSessionUserOrgId(HttpServletRequest request) {
		String userOrgId = "";
		if(request!=null) {
			Object userOrgObj = request.getSession().getAttribute("zorg");
			if(userOrgObj!=null && userOrgObj instanceof z_org) {
				z_org org = (z_org) userOrgObj;
				userOrgId = org.getZid();
			}
		}
		return userOrgId;
	}

	/**
	 * 根据用户ZID获取分配的组织
	 * @param UserZId
	 * @return
	 */
	public List<z_org> GetUserOrg(String UserZId){
		List<z_org> listOrg = new ArrayList<z_org>();
		if(UserZId.equals(z.sp.get("super_user"))) {
			listOrg.add(GetOrgForOrgId("0000"));
		}else {
			if(!"".equals(UserZId) && UserZId!=null) {
				String sql = "SELECT oc.* FROM z_org oc LEFT JOIN z_org_user ou ON oc.zid = ou.pid INNER JOIN z_user zu ON ou.userid = zu.zid where zu.user_id = '"+UserZId+"' OR zu.tel = '"+UserZId+"'";
				List<HashMap> userOrgList = sqlSession.selectList("select", sql);
				for (HashMap userOrgMap : userOrgList) {
					z_org org = BeanUtil.MapToBean(userOrgMap, z_org.class);
					listOrg.add(org);
				}
			}
		}
		return listOrg;
	}

	/**
	 * 根据用户ZID获取分配的组织
	 */
	public z_org GetOrg(String zid){
		z_org org = null;
		if(!"".equals(zid) && zid!=null) {
			String sql = "SELECT * FROM z_org where zid = '"+zid+"'";
			HashMap orgmap = sqlSession.selectOne("select",sql);
			if(orgmap!=null) {
				org = BeanUtil.MapToBean(orgmap, z_org.class);
			}
		}
		return org;
	}


	/**
	 * 根据用户ZID获取分配的组织
	 */
	public z_org GetOrgForOrgId(String org_id){
		z_org org = null;
		if(!"".equals(org_id) && org_id!=null) {
			String sql = "SELECT * FROM z_org where org_id = '"+org_id+"'";
			HashMap orgmap = sqlSession.selectOne("select",sql);
			if(orgmap!=null) {
				org = BeanUtil.MapToBean(orgmap, z_org.class);
			}
		}
		return org;
	}


	/**
	 * 获取用户ID
	 * @return
	 */
	public static String getUserId() {
		if(z.isNotNull(RequestContextHolder.getRequestAttributes())) {
			HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			return GetSessionUserId(request);
		}else {
			return "";
		}
	}


	/**
	 * 	从Session中获取信息保存到Bean中
	 * @param bean
	 */
	protected void GetSessionInfoToBean(HashMap<String,String> bean,HttpServletRequest request) {
		//获取Session中的用户
		if(request.getSession().getAttribute("zuser")!=null && request.getSession().getAttribute("zuser") instanceof z_user) {
			z_user user = (z_user) request.getSession().getAttribute("zuser");
			bean.put("session_userid", user.getZid());
		}
		//获取Session中的组织
		if(request.getSession().getAttribute("zorg")!=null && request.getSession().getAttribute("zorg") instanceof z_org) {
			z_org org = (z_org) request.getSession().getAttribute("zorg");
			bean.put("session_orgid", org.getZid());
		}
		//根据request信息判读是否为移动端访问
		if(z.isNotNull(request)) {
			LiteDeviceResolver deviceResolver = new LiteDeviceResolver();
			Device device = deviceResolver.resolveDevice(request);
			if(device.isMobile() || device.isTablet()) {
				bean.put("is_mobile", "1");
			}else {
				bean.put("is_mobile", "0");
			}
		}

	}



	/**
	 * 获取用户消息列表
	 * touserid 接收消息人
	 * @return
	 */
	protected Result GetUserMessageList(String touserid){
		Result result = new Result();
		if(z.isNotNull(touserid)) {
			StringBuffer sql = new StringBuffer();
			sql.append("select c.zid,c.user_name, ISNULL(d.userid) isonline,count(m.zid) messagecount,c.photo ");
			sql.append("from z_user c  ");
			sql.append("left join z_user_online d on c.zid = d.userid ");
			sql.append("left join z_messages m on c.zid = m.fromuserid and m.is_open = 0 and m.touserid = '"+touserid+"' ");
			sql.append("where c.is_start = 1  ");
			sql.append("GROUP BY c.zid ");
			sql.append("order by d.userid desc, c.seq");

			List<HashMap<String,String>> messageList = sqlSession.selectList("select", sql);
			if(z.isNotNull(messageList) && messageList.size()>0) {
				result.setCode(Code.SUCCESS);
				result.setMsg("ok");
				result.setData(messageList);
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("list is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("touserid is null");
		}

		return result;
	}

	/**
	 * 发送OA通知
	 * @param form_userid 发送人
	 * @param to_userid 接收人
	 * @param message 消息
	 * @return
	 */
	public Result SentOaMassage(String form_userid,String to_userid,String message) {
		Result result = new Result();
		if(z.isNotNull(message)) {
			z_user form_user = sqlSession.selectOne("z_user_select_zid", form_userid);
			z_user to_user = sqlSession.selectOne("z_user_select_zid", to_userid);
			if(z.isNotNull(form_user)) {
				if(z.isNotNull(to_user)) {
					String to_user_email = to_user.getEmail();
					if(z.isNotNull(to_user_email)) {
						//发送信息
						StringBuffer messageBuffer = new StringBuffer();
						messageBuffer.append("通知内容："+message).append("\r\n");
						messageBuffer.append("发送人："+form_user.getUser_name()).append("\r\n");
						result = EmailUtil.sent(to_user_email, "OA系统通知", message);
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("发送OA通知出错|接收人邮箱为空");
					}
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("发送OA通知出错|接收人为空");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("发送OA通知出错|发送人为空");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("发送OA通知出错|发送消息为空");
		}

		return result;
	}

	/**
	 * 判读是否是手机设备访问
	 * @return
	 */
	protected boolean isMobile(HttpServletRequest request) {
		boolean result = false;
		if(z.isNotNull(request)) {
			LiteDeviceResolver deviceResolver = new LiteDeviceResolver();
			Device device = deviceResolver.resolveDevice(request);
			if(device.isMobile() || device.isTablet()) {
				result = true;
			}
		}
		return result;
	}


	/**
	 * 创建连续数字编号
	 */
	public String newContinuityNumber(String number) throws Exception {
		String num = "";
		if(z.isNull(number)){
			number = "z_default_number";
		}
		z_sequence s = sqlSession.selectOne("z_sequence_select_sql", "SELECT * FROM z_sequence WHERE number = '"+number+"'");
		if(z.isNull(s)){
			//未找到发号器，直接创建一个新的
			s = new z_sequence();
			s.setZid(number);
			s.setNumber(number);
			s.setName(number);
			s.setMax_with("999999999999999");
			s.setNow_with("0");
			s.setIncrement("1");
			s.setPattern("00000000000000");
			int n = sqlSession.insert("z_sequence_insert",s);
			if(n!=1){
				z.Exception("创建【"+number+"】发号器失败|执行insert返回记录条数："+n);
			}
		}

		//生成新号
		int new_now_with = getNewNowWithNum(s);

		//格式化新号
		if(z.isNotNull(s.getPrefix())) {
			num = s.getPrefix()+MathUtil.FormatNumber(new_now_with, s.getPattern());
		}else {
			num = MathUtil.FormatNumber(new_now_with, s.getPattern());
		}

		return num;
	}

	private int getNewNowWithNum(z_sequence s) throws Exception {
		int new_now_with = new Integer(s.getNow_with()) + new Integer(s.getIncrement());
		//保存新号
		int updatecount = sqlSession.update("update", "UPDATE z_sequence SET now_with = "+new_now_with+" ,zversion = zversion + 1  WHERE zversion = "+s.getZversion()+" and number = '"+s.getNumber()+"' AND now_with = '"+s.getNow_with()+"'");
		if(updatecount==0) {
			//未保存成功，重新发号。等待1秒
			Thread.sleep(1000);

			//重新获取
			z_sequence s2 = sqlSession.selectOne("z_sequence_select_sql", "SELECT * FROM z_sequence WHERE number = '"+s.getNumber()+"'");
			new_now_with = getNewNowWithNum(s2);
		}
		return new_now_with;
	}


	/**
	 * 判读是否是无法登录状态方法
	 * @param methodName
	 * @param method
	 * @return
	 * @throws Exception customer_main
	 */
	protected boolean isSystemNoStateFunction(String methodName, HandlerMethod method) throws Exception {
		if(methodName.equals("default_index")) {//默认首页
			return true;
		}else if(methodName.equals(z.system_login)) {//登录页面
			return true;
		}else if(methodName.equals(z.customer_login)) {//客户登录页面
			return true;
		}else if(methodName.equals("UserLogin")) {//登录
			return true;
		}else if(methodName.equals("UserLoginJson")) {//用户登录返回JSON
			return true;
		}else if(methodName.equals("CustomerLogin")) {//客户登录
			return true;
		}else if(methodName.equals("customer_add")) {//客户新增页面
			return true;
		}else if(methodName.equals("customer_register")) {//客户注册
			return true;
		}else if(methodName.equals("customer_main")) {//客户主页
			return true;
		}else if(methodName.equals("getUserOrgForUserId")) {//根据用户ID获取用户组织信息
			return true;
		}else if(methodName.equals("LoadParameter")) {//更新系统缓存数据
			return true;
		}else if(methodName.equals("upload")) {//上传文件im_getimg
			return true;
		}else if(methodName.equals("im_getimg")) {//im选择图片文件
			return true;
		}else if(methodName.equals("zs")) {//调用ZS接口
			return true;
		}else if(methodName.equals("UserExit")) {//UserExit
			return true;
		}else if(methodName.equals("customer_exit")) {//CustomerExit
			return true;
		}else if(methodName.equals("openjsp")) {//通用打开jsp页面
			return true;
		}else if(methodName.equals("404")) {//404
			return true;
		}else if(methodName.equals("500")) {//500
			return true;
		}else if(methodName.equals("deleteServerFile")) {//后台接口调用到本机的deleteServerFile，删除本机文件
			return true;
		}else{
			return false;
		}



	}

	/**
	 * 保存日志
	 * @param request
	 * @param method
	 */
	public static void Log(HttpServletRequest request, HandlerMethod method) {
		// TODO 自动生成的方法存根

	}

	/**
	 * 保存到z.controllers中
	 * @param method
	 */
	protected void SaveController(HandlerMethod method) {
		if("true".equals(z.sp.get("is_start_controller"))){
			String methodName = method.getMethod().getName();
			z_controller c = z.controllers.get(methodName);
			if(z.isNull(c)) {
				//判读数据库是否在该方法
				int isCount = sqlSession.selectOne("selectoneint", "select count(*) from z_controller where controller = '"+methodName+"'");
				if(isCount == 0) {
					c = new z_controller();
					String zid = z.newZid("z_controller");
					c.setZid(zid);
					c.setController(methodName);//方法名
					String returnClass =  method.getMethod().getReturnType().getName();
					String returnclassName = returnClass.substring(returnClass.lastIndexOf(".")+1).toLowerCase();
					c.setController_type(returnclassName);//返回类型
					c.setReturn_type(returnClass);//返回类
					c.setName(methodName);//描述
					c.setIs_monitor("1");
					int num = sqlSession.insert("z_controller_insert", c);
					if(num!=1) {
						z.Error("保存请求信息到z_controller异常|"+methodName);
					}else {
						//参数
						//Parameter[] plist = method.getMethod().getParameters();
						MethodParameter[] plist = method.getMethodParameters();
						for (int i = 0; i < plist.length; i++) {
							MethodParameter p = plist[i];
							z_controller_parameter d = new z_controller_parameter();
							d.setPid(zid);
							d.setZid(z.newZid("z_controller_parameter"));
							d.setParameter(p.getParameterName());
							d.setParameter_types(p.getParameterType().getSimpleName());
							d.setName(p.getParameterName());
							int dnum = sqlSession.insert("z_controller_parameter_insert", d);
							if(dnum!=1) {
								z.Error("保存请求信息到z_controller异常,保存参数信息异常|"+p.getParameterName());
							}
						}
					}
				}else {
					//更新缓存数据
					initControllers();
				}
			}
		}
	}

	/**
	 *	 保存系统日志
	 */
	public void SaveSystemLog(z_log log) {
		if(z.isNotNull(log) && z.isNotNull(sqlSession) && "true".equals(z.sp.get("isInterceptorLog"))) {
			sqlSession.insert("z_log_insert", log);
		}
	}

	/**
	 * 根据客户ID 登陆账号 / 手机号 /邮箱 /ZID 查询客户
	 * @param customid
	 * @return
	 * @throws Exception
	 */
	public Result GetCustomer(String customid) throws Exception {
		Result result = new Result();
		crm_customer c = null;
		String sql = "select * from crm_customer where zid = '"+customid+"' or number = '"+customid+"' or tel = '"+customid+"' or email = '"+customid+"'  or id_number = '"+customid+"'";
		List<crm_customer> customerList = sqlSession.selectList("crm_customer_select_sql", sql);
		if(z.isNotNull(customerList) && customerList.size()>0) {
			if(customerList.size()>1) {
				result.setError("登录账号产生重复信息，请使用其它登录号进行登录");
			}else {
				c = customerList.get(0);
				if("1".equals(c.getIs_enabled())){
					result.setSuccess(c);
				}else{
					result.setError("客户账号未启用");
				}
			}
		}else {
			result.setError("根据【"+customid+"】未从获取到客户信息");
		}
		return result;
	}

	/**
	 * 缓存客户信息
	 * @param request
	 * @param customer
	 * @return
	 */
	public boolean SetSessionCustomer(HttpServletRequest request,crm_customer customer) {
		boolean result = false;
		if(request!=null && customer!=null) {
			//保存用户信息到Session中
			request.getSession().setAttribute("zcustomer", customer);
		}
		return result;
	}



}
